<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <div class="flex">
      <!-- 左侧分类树 -->
      <div class="w-1/3 pr-4 border-r border-gray-200">
        <div class="text-sm font-medium mb-2">产品分类</div>
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          highlight-current
          :default-expand-all="true"
          @node-click="handleNodeClick"
          class="category-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <span class="node-label" :class="{ 'text-blue-500': data.id === formData.classCode }">
                {{ node.label }}
              </span>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 右侧表单 -->
      <div class="w-2/3 pl-4">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          v-loading="formLoading"
        >
          <!-- 第一行：产品名称 + 英文名称 -->
          <div class="flex mb-4">
            <el-form-item label="产品名称:" prop="name" class="flex-1 pr-4">
              <el-input v-model="formData.name" placeholder="请输入..." />
            </el-form-item>
            <el-form-item label="英文名称:" prop="nameEn" class="flex-1">
              <el-input v-model="formData.nameEn" placeholder="请输入..." />
            </el-form-item>
          </div>

          <!-- 第二行：拉丁文名称 + 产品性状 -->
          <div class="flex mb-4">
            <el-form-item label="拉丁文名称:" prop="nameLatin" class="flex-1 pr-4">
              <el-input v-model="formData.nameLatin" placeholder="请输入..." />
            </el-form-item>
            <el-form-item label="产品性状:" prop="shape" class="flex-1">
              <el-input v-model="formData.shape" placeholder="请输入..." />
            </el-form-item>
          </div>

          <!-- 第三行：颜色外观 + 储存条件 -->
          <div class="flex mb-4">
            <el-form-item label="颜色外观:" prop="exterior" class="flex-1 pr-4">
              <el-input v-model="formData.exterior" placeholder="请输入..." />
            </el-form-item>
            <el-form-item label="储存条件:" prop="store" class="flex-1">
              <el-input v-model="formData.store" placeholder="请输入..." />
            </el-form-item>
          </div>

          <!-- 产品规格（独占一行） -->
          <el-form-item label="产品规格:" prop="specs">
            <el-input
              v-model="formData.specs"
              placeholder="请输入..."
              type="textarea"
              :rows="6"
              resize="none"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ProdInfoApi, ProdInfoVO } from '@/api/product/prodinfo'
import { BaseProductClassApi } from '@/api/business/baseproductclass'
import { handleTree } from '@/utils/tree'
import { nextTick } from 'vue'

/** 产品信息 表单 */
defineOptions({ name: 'ProdInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  classCode: undefined,
  name: undefined,
  nameEn: undefined,
  nameLatin: undefined,
  specs: undefined,
  shape: undefined,
  exterior: undefined,
  store: undefined,
  remark: undefined,
})
const formRules = reactive({
  classCode: [
    { required: true, message: '请选择产品分类', trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref

// 树形结构
const treeRef = ref() // 树组件 Ref
const treeData = ref([])
const treeProps = {
  children: 'children',
  label: 'name'
}

/** 获取树形分类数据 */
const getTreeData = async () => {
  try {
    const data = await BaseProductClassApi.getBaseProductClassList({})
    data.sort((a, b) => {
      if (a.pid === b.pid) {
        return a.orderId - b.orderId
      }
      return a.pid - b.pid
    })
    treeData.value = handleTree(data, 'id', 'pid')
  } catch (error) {
    console.error('获取分类树失败:', error)
    message.error('获取分类树失败')
  }
}

/** 树节点点击事件 */
const handleNodeClick = (data: any) => {
  formData.value.classCode = data.id
  // 强制重新渲染树组件以更新样式
  treeRef.value?.setCurrentKey(data.id)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  
  // 获取分类树数据
  await getTreeData()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProdInfoApi.getProdInfo(id)
      // 设置默认选中的分类节点
      nextTick(() => {
        if (formData.value.classCode) {
          treeRef.value?.setCurrentKey(formData.value.classCode)
        }
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProdInfoVO
    if (formType.value === 'create') {
      await ProdInfoApi.createProdInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProdInfoApi.updateProdInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    classCode: undefined,
    name: undefined,
    nameEn: undefined,
    nameLatin: undefined,
    specs: undefined,
    shape: undefined,
    exterior: undefined,
    store: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.category-tree {
  width: 100%;
  height: 400px;
  overflow-y: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  font-size: 14px;
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 确保蓝色文字样式优先级足够高 */
:deep(.el-tree .el-tree-node .tree-node .text-blue-500) {
  color: #3b82f6 !important;
}
</style>